<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>获取 GitHub GHU</title>
    <style>
        :root {
            --primary-color: #0066CC;
            --hover-color: #0256A8;
            --background-light: #ffffff;
            --text-color: #1d1d1f;
            --input-background: #fbfbfd;
            --input-border: #d2d2d7;
            --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

        body, html {
            height: 100%;
            margin: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Text', 'SF Pro Icons', 'Helvetica Neue', sans-serif;
            background-color: var(--background-light);
            color: var(--text-color);
        }

        .login-container {
            background-color: var(--background-light);
            padding: 3.5em 4em;
            border-radius: 20px;
            box-shadow: 0 4px 24px rgba(0, 0, 0, 0.08);
            text-align: center;
            width: 90%;
            max-width: 440px;
            transition: var(--transition);
        }

        h1 {
            font-size: 24px;
            font-weight: 500;
            margin-bottom: 1.5em;
            color: var(--text-color);
        }

        .form-box {
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        input {
            width: 100%;
            padding: 12px 16px;
            margin: 6px 0;
            border: 1px solid var(--input-border);
            border-radius: 12px;
            background-color: var(--input-background);
            font-size: 15px;
            transition: var(--transition);
            outline: none;
            box-sizing: border-box;
        }

        input:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 4px rgba(0, 102, 204, 0.1);
        }

        .submit-button {
            width: 90%;
            padding: 12px;
            margin-top: 24px;
            border: none;
            border-radius: 12px;
            background-color: var(--primary-color);
            color: white;
            font-size: 15px;
            font-weight: 500;
            cursor: pointer;
            transition: var(--transition);
            text-align: center;
        }

        .submit-button:hover {
            background-color: var(--hover-color);
            transform: translateY(-1px);
        }

        .submit-button:active {
            transform: translateY(0);
        }

        .footer {
            margin-top: 32px;
            font-size: 13px;
            color: #86868b;
        }

        .footer a {
            color: var(--primary-color);
            text-decoration: none;
            transition: var(--transition);
        }

        .footer a:hover {
            text-decoration: underline;
        }

        .code-content {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 60px;
            margin: 20px 0;
        }

        #code {
            font-size: 32px;
            letter-spacing: 8px;
            font-weight: 600;
            color: var(--primary-color);
            font-family: SF Mono, monospace;
        }

        .measure-time {
            background-color: transparent;
            border: 1px solid var(--primary-color);
            color: var(--primary-color);
        }

        #token-box {
            display: none;
            animation: fadeIn 0.3s ease-in-out;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        /* Dark mode */
        @media (prefers-color-scheme: dark) {
            :root {
                --background-light: #1d1d1f;
                --text-color: #f5f5f7;
                --input-background: #2c2c2e;
                --input-border: #3a3a3c;
            }

            .login-container {
                box-shadow: 0 4px 24px rgba(0, 0, 0, 0.2);
            }

            input::placeholder {
                color: #86868b;
            }
        }
    </style>
</head>
<body>
    <div class="login-container">
        <h1>获取 GitHub GHU</h1>
        <div class="form-box">
            <div id="token-box">
                <div class="code-content">
                    <div id="code"></div>
                </div>
                <input type="text" id="token" placeholder="正在获取ghu_" readonly/>
                <div id="timeing" class="submit-button measure-time">剩余时间: 900 秒</div>
            </div>
            <div id="submit-btn" class="submit-button" onclick="onSubmit()">登录 GitHub 获取授权码</div>
        </div>

        <div class="footer">
            © 2024 Open Source Contributors
        </div>
    </div>

    <script type="text/javascript">
        let device_code = null;
        let timer = null;

        function countDown(time = 900) {
            const timeing = document.getElementById('timeing');
            timer = setInterval(() => {
                time -= 1;
                timeing.innerText = `剩余时间: ${time} 秒`;
                if (time <= 0) {
                    clearInterval(timer);
                    document.getElementById('submit-btn').style.display = 'block';
                    timeing.style.display = 'none';
                    alert("授权码已过期，请重新获取");
                    window.location.reload();
                }
            }, 1000);
        }

        async function onSubmit() {
            const response = await fetch('/github/login/device/code', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            if (response.status !== 200) {
                alert('获取授权码失败')
                window.location.reload()
                return
            }
            const resultJson = await response.json()
            confirm(`打开浏览器访问: ${resultJson.verification_uri}, 并输入授权码: ${resultJson.user_code}`)
            copyCode(resultJson.user_code)
            device_code = resultJson.device_code
            document.getElementById('submit-btn').style.display = 'none';
            document.getElementById('token-box').style.display = 'block';
            document.getElementById("code").innerText = resultJson.user_code;
            countDown(resultJson.expires_in);
            window.open(resultJson.verification_uri);
            // 根据user_code获取ghu_token
            await getGhuToken();
        }

        function copyCode(user_code) {
            const input = document.createElement('input');
            input.value = user_code;
            document.body.appendChild(input);
            input.select();
            document.execCommand('copy');
            document.body.removeChild(input);
        }

        async function getGhuToken() {
            await new Promise(resolve => setTimeout(resolve, 5000))
            const response = await fetch('/github/login/ghu-token', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({device_code})
            })
            if (response.status !== 200) {
                alert('获取ghu_token失败')
                window.location.reload()
                return false;
            }
            const resultJson = await response.json()
            if (resultJson.error === "slow_down" && resultJson.error_description === "Too many requests have been made in the same timeframe.") {
                await new Promise(resolve => setTimeout(resolve, resultJson.interval * 1000))
            }

            const access_token = resultJson?.access_token || null
            if (access_token !== null) {
                document.getElementById('token').value = access_token
                clearInterval(timer);
                document.getElementById("timeing").style.display = 'none';
                document.getElementById("code").style.display = 'none';
                return false;
            }
            await getGhuToken()
        }
    </script>
</body>
</html>
